package com.xdcplus.web.service.tool.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.xdcplus.core.utils.BeanUtils;
import com.xdcplus.exceptions.XdcWebException;
import com.xdcplus.mom.constants.NumberConstant;
import com.xdcplus.mom.enums.ResponseEnum;
import com.xdcplus.mp.service.impl.BaseServiceImpl;
import com.xdcplus.mp.utils.PageableUtils;
import com.xdcplus.mp.utils.PropertyUtils;
import com.xdcplus.pager.vo.PageVO;
import com.xdcplus.web.common.pojo.dto.tool.ToolGroupDTO;
import com.xdcplus.web.common.pojo.dto.tool.ToolGroupFilterDTO;
import com.xdcplus.web.common.pojo.entity.tool.ToolGroup;
import com.xdcplus.web.common.pojo.query.tool.ToolGroupQuery;
import com.xdcplus.web.common.pojo.vo.tool.ToolGroupVO;
import com.xdcplus.web.mapper.tool.ToolGroupMapper;
import com.xdcplus.web.service.tool.ToolGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/**
 * 1-设备对应群组信息(ToolGroup)表服务实现类
 *
 * @author Bullion.Yan
 * @since 2023-02-14 16:26:25
 */
@Slf4j
@Service("toolGroupService")
public class ToolGroupServiceImpl extends BaseServiceImpl<ToolGroupMapper, ToolGroup, ToolGroup, ToolGroupVO> implements ToolGroupService {

    @Autowired
    protected ToolGroupMapper toolGroupMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean saveToolGroup(ToolGroupDTO toolGroupDTO) {
        Long codeCount = toolGroupMapper.selectCount(new QueryWrapper<ToolGroup>().eq("GROUP_CODE", toolGroupDTO.getGroupCode()));
        Assert.isTrue(Validator.equal(codeCount,NumberConstant.ZERO.longValue()),ResponseEnum.CODE_ALREADY_EXISTS.getMessage());

        ToolGroup toolGroup = new ToolGroup();
        BeanUtil.copyProperties(toolGroupDTO, toolGroup);
        toolGroup.setCreatedTime(new Timestamp(DateUtil.current()));
        
        return this.save(toolGroup);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updateToolGroup(ToolGroupDTO toolGroupDTO) {

        ToolGroup toolGroup = this.getById(toolGroupDTO.getId());
        if (ObjectUtil.isNull(toolGroup)) {
            log.error("updateToolGroup() The ToolGroup does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }

        BeanUtil.copyProperties(toolGroupDTO, toolGroup);
        toolGroup.setUpdatedUser(toolGroupDTO.getUpdatedUser());
        toolGroup.setUpdatedTime(new Timestamp(DateUtil.current()));

        return this.updateById(toolGroup);
    }

    @Override
    public Boolean saveOrUpdateBatch(List<ToolGroup> toolGroupList) {

        toolGroupList.forEach(toolGroup -> {
            ToolGroup toolGroupParam = new ToolGroup();
            toolGroupParam.setId(toolGroup.getId());
            if (ObjectUtil.isNotNull(toolGroup.getId())) {
                toolGroup.setId(toolGroup.getId());
                toolGroup.setUpdatedTime(new Timestamp(DateUtil.current()));
                LambdaUpdateWrapper<ToolGroup> lambdaUpdate = Wrappers.lambdaUpdate();
                lambdaUpdate.eq(ToolGroup::getId, toolGroup.getId());
                update(toolGroup, lambdaUpdate);
            } else {
                toolGroup.setCreatedTime(new Timestamp(DateUtil.current()));
                save(toolGroup);
            }
        });
        return true;
    }

    @Override
    public Boolean saveOrUpdateBatchByDTOList(List<ToolGroupDTO> toolGroupDTOList) {

        List<ToolGroup> toolGroupList = BeanUtils.copyProperties(toolGroupDTOList, ToolGroup.class);
        return saveOrUpdateBatch(toolGroupList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteToolGroupLogical(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        ToolGroup toolGroup = this.getById(id);

        if (ObjectUtil.isNull(toolGroup)) {
            log.error("deleteToolGroup() The ToolGroup does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }
        return this.removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deleteToolGroupByIds(String ids) {
        Assert.notNull(ids, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());
		List<String> idList = Arrays.asList(ids.split(","));
		if(CollectionUtil.isEmpty(idList)){
           throw new XdcWebException(ResponseEnum.ERROR);
       }
		idList.forEach(id->{
			ToolGroup toolGroup = this.getById(id);
			if (ObjectUtil.isNull(toolGroup)) {
				log.error("deleteToolGroup() The ToolGroup does not exist or has been deleted");
				throw new XdcWebException(ResponseEnum.ERROR);
			}
		});
		
        return this.removeByIds(idList);
    }

    private List<ToolGroup> queryToolGroupList(ToolGroupFilterDTO toolGroupFilterDTO) {
        ToolGroupQuery toolGroupQuery = BeanUtil.copyProperties(toolGroupFilterDTO, ToolGroupQuery.class);

        return toolGroupMapper.queryToolGroup(toolGroupQuery);
    }

    @Override
    public List<ToolGroupVO> queryToolGroupVOList(ToolGroupFilterDTO toolGroupFilterDTO) {
        return this.objectConversion(queryToolGroupList(toolGroupFilterDTO));
    }

    @Override
    public PageVO<ToolGroupVO> queryToolGroup(ToolGroupFilterDTO toolGroupFilterDTO) {
        PageVO<ToolGroupVO> pageVO = new PageVO<>();

        if (toolGroupFilterDTO.getCurrentPage() > NumberConstant.ZERO) {
            PageableUtils.basicPage(toolGroupFilterDTO.getCurrentPage(), toolGroupFilterDTO.getPageSize(),
                    toolGroupFilterDTO.getOrderType(), toolGroupFilterDTO.getOrderField());
        }

        List<ToolGroup> toolGroupList = queryToolGroupList(toolGroupFilterDTO);

        PageInfo<ToolGroup> pageInfo = new PageInfo<>(toolGroupList);
        PropertyUtils.copyProperties(pageInfo, pageVO, this.objectConversion(toolGroupList));

        return pageVO;
    }

    @Override
    public ToolGroupVO queryToolGroupById(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        return this.objectConversion(this.getById(id));
    }
    @Override
    public ToolGroupVO queryToolGroupByGroupCode(String groupCode) {
        return this.objectConversion(toolGroupMapper.queryToolGroupByGroupCode(groupCode));
    }

}
